<template>
  <div style="margin-top: 50px">
    <el-form :model="state" ref="productAttrForm" label-width="120px" class="form-inner-container" size="small">
      <el-form-item label="属性类型：">
        <el-cascader v-model="productAttributeCategoryValues[0]" :options="productAttributeCategoryOptions" placeholder="请选择属性类型" @change="handleProductAttrChange"> </el-cascader>
      </el-form-item>
      <el-form-item label="商品规格：">
        <el-card v-if="type1 && type2" shadow="never" class="cardBg">
          <div v-for="(productAttr, idx) in selectProductAttr" :key="productAttr.id">
            {{ productAttr.name }}：
            <div v-if="productAttr.handAddStatus === 0">
              <el-checkbox v-for="item in getInputListArr(productAttr.inputList)" :checked="getDisabled(productAttr.values, item)" @change="productAttrChange(item, productAttr.name)" :label="item" :key="item" class="littleMarginLeft" size="default"></el-checkbox>
            </div>
            <div v-if="productAttr.handAddStatus === 1">
              <div v-for="item in selectProductAttr[idx].options" :key="item" style="display: inline-block" class="littleMarginLeft">
                <el-checkbox :checked="getDisabled(productAttr.values, item)" @change="productHandAddStatusAttrChange(idx, item)" :label="item" :key="item" class="littleMarginLeft" size="default"></el-checkbox>
                <el-button class="littleMarginLeft" @click="handleRemoveProductAttrValue(idx, item)">删除 </el-button>
              </div>
              <el-input v-model="addProductAttrValue" style="width: 160px; margin-left: 10px" clearable></el-input>
              <el-button class="littleMarginLeft" @click="handleAddProductAttrValue(idx)">增加</el-button>
            </div>
          </div>
        </el-card>
        <el-table style="width: 100%; margin-top: 20px" :data="state.skuStockList" border>
          <el-table-column v-for="(item, index) in selectProductAttr" :label="item.name" :key="item.id" align="center">
            <template v-slot="scope">
              {{ getProductSkuSp(scope.row, index) }}
            </template>
          </el-table-column>
          <el-table-column label="销售价格" width="100" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.price"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="促销价格" width="100" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.promotionPrice"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" width="80" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.stock"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="库存预警值" width="80" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.lowStock"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="SKU编号" width="160" align="center">
            <template v-slot="scope">
              <el-input v-model="scope.row.skuCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template v-slot="scope">
              <el-button @click="handleRemoveProductSku(scope.$index, scope.row)">删除 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" style="margin-top: 20px" @click="handleRefreshProductSkuList">刷新列表 </el-button>
        <el-button type="primary" size="default" style="margin-top: 20px" @click="handleSyncProductSkuPrice">同步价格 </el-button>
        <el-button type="primary" size="default" style="margin-top: 20px" @click="handleSyncProductSkuStock">同步库存 </el-button>
      </el-form-item>
      <el-form-item label="属性图片：" v-if="hasAttrPic">
        <el-card shadow="never" class="cardBg">
          <div v-for="(item, index) in selectProductAttrPics" :key="index">
            <span>{{ item.name }}:</span>
            <SingleUpload @uploadImage="singleUploadImage" :type="item.name" v-model:value="item.pic" style="width: 300px; display: inline-block; margin-left: 10px"></SingleUpload><br />
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="商品参数：">
        <el-card shadow="never" class="cardBg" v-if="type1 && type2">
          <div v-for="(item, paramIdx) in selectProductParam" :key="item.id" :class="{ littleMarginTop: paramIdx !== 0 }">
            <div class="paramInputLabel">{{ item.name }}:</div>
            <el-cascader v-if="item.inputType === 1" v-model="item.value" :options="productParamOptions(paramIdx)" placeholder="请选择参数类型" @change="productParamOptionsChange(paramIdx, item.value)"> </el-cascader>
            <el-input v-else class="paramInput" v-model="selectProductParam[paramIdx].value"></el-input>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="商品相册：">
        <MultiUpload v-model:value="selectProductPics" @uploadImage="multiUploadImage"></MultiUpload>
      </el-form-item>
      <el-form-item label="商品详情：">
        <el-tabs v-model="activeHtmlName" type="card">
          <el-tab-pane label="电脑端详情" name="pc">
            <Tinymce :width="595" :height="300" v-model:value="state.detailHtml" @getContent="getPcContent"></Tinymce>
          </el-tab-pane>
          <el-tab-pane label="移动端详情" name="mobile">
            <Tinymce :width="595" :height="300" v-model:value="state.detailMobileHtml" @getContent="getIphoneContent"></Tinymce>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button size="default" @click="handlePrev">上一步，填写商品促销</el-button>
        <el-button size="default" type="primary" @click="handleNext">下一步，选择商品关联</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { fetchList as fetchProductAttrCateList } from '@/plugins/productAttrCate'
import { fetchList as fetchProductAttrList } from '@/plugins/productAttr'
import SingleUpload from '@/components/Upload/singleUpload.vue'
import MultiUpload from '@/components/Upload/multiUpload.vue'
import Tinymce from '@/components/Tinymce/MyEdit.vue'
import { reactive, ref, onBeforeMount, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  value: Object,
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['nextStep', 'prevStep'])

let state = reactive(props.value)

let hasEditCreated = ref(false)
//商品属性分类下拉选项
let productAttributeCategoryOptions = reactive([])
let productAttributeCategoryValues = reactive([])
//选中的商品属性
let selectProductAttr = reactive([])
//选中的商品参数
let selectProductParam = reactive([])
//选中的商品属性图片
let selectProductAttrPics = reactive([])
//可手动添加的商品属性
let addProductAttrValue = ref('')
//商品富文本详情激活类型
let activeHtmlName = ref('pc')

let type1 = ref(false)
let type2 = ref(false)

let hasAttrPic = ref(false)

const productId = computed(() => {
  return state.id
})

function productParamOptionsChange(idx, item) {
  selectProductParam[idx].value = item[0]
}

function multiUploadImage(val) {
  selectProductPics.value = val
}

function singleUploadImage(val, type) {
  for (let i = 0; i < state.skuStockList.length; i++) {
    let spData = JSON.parse(state.skuStockList[i].spData)
    if (type === spData[0].value) {
      state.skuStockList[i].pic = val
    }
  }
}

function getPcContent(value, myValue) {
  state.detailHtml = myValue
}

function getIphoneContent(value, myValue) {
  state.detailMobileHtml = myValue
}

function getDisabled(itemValue, value) {
  return itemValue.includes(value)
}

function productParamOptions(index) {
  var options = []
  var names = selectProductParam[index].inputList.split(',')
  for (var i = 0; i < names.length; i++) {
    options.push({
      label: names[i],
      value: names[i]
    })
  }
  return options
}

function productHandAddStatusAttrChange(idx, itemValue) {
  if (selectProductAttr[idx].options.includes(itemValue)) {
    if (selectProductAttr[idx].values.includes(itemValue)) {
      selectProductAttr[idx].values = selectProductAttr[idx].values.filter(item => {
        return item !== itemValue
      })
    } else {
      selectProductAttr[idx].values.push(itemValue)
    }
  }
}

function productAttrChange(value, arrName) {
  var index = 0
  for (var i = 0; i < selectProductAttr.length; i++) {
    if (selectProductAttr[i].name === arrName) {
      index = i
    }
  }

  if (selectProductAttr[index].values.includes(value)) {
    selectProductAttr[index].values = selectProductAttr[index].values.filter(function (item) {
      return item !== value
    })
  } else {
    selectProductAttr[index].values.push(value)
  }
}

const selectProductPics = computed({
  get: function () {
    let pics = []
    if (state.pic === undefined || state.pic == null || state.pic === '') {
      return pics
    }
    pics.push(state.pic)
    if (state.albumPics === undefined || state.albumPics == null || state.albumPics === '') {
      return pics
    }
    let albumPics = state.albumPics.split(',')
    for (let i = 0; i < albumPics.length; i++) {
      pics.push(albumPics[i])
    }
    return pics
  },
  set: function (newValue) {
    if (newValue == null || newValue.length === 0) {
      state.pic = null
      state.albumPics = null
    } else {
      state.pic = newValue[0]
      state.albumPics = ''
      if (newValue.length > 1) {
        for (let i = 1; i < newValue.length; i++) {
          state.albumPics += newValue[i]
          if (i !== newValue.length - 1) {
            state.albumPics += ','
          }
        }
      }
    }
  }
})

onBeforeMount(() => {
  getProductAttrCateList()
  productAttributeCategoryValues.push(state.productAttributeCategoryId)
  getProductAttrList(0, state.productAttributeCategoryId)
  getProductAttrList(1, state.productAttributeCategoryId)
})

watch(productId, newValue => {
  if (!props.isEdit) return
  if (hasEditCreated.value) return
  if (newValue === undefined || newValue == null || newValue === 0) return
  handleEditCreated()
})

function handleEditCreated() {
  //根据商品属性分类id获取属性和参数
  if (state.productAttributeCategoryId != null && state.productAttributeCategoryId != 0) {
    productAttributeCategoryValues = reactive([])
    productAttributeCategoryValues.push(state.productAttributeCategoryId)
  }
  hasEditCreated.value = true
}

function getProductAttrCateList() {
  let param = { pageNum: 1, pageSize: 100 }
  fetchProductAttrCateList(param).then(response => {
    let list = response.data.list
    for (let i = 0; i < list.length; i++) {
      productAttributeCategoryOptions.push({ label: list[i].name, value: list[i].id })
    }
  })
}

function getProductAttrList(type, cid) {
  let param = { pageNum: 1, pageSize: 100, type: type }
  fetchProductAttrList(cid, param).then(response => {
    let list = response.data.list
    if (type === 0) {
      selectProductAttr = reactive([])
      for (let i = 0; i < list.length; i++) {
        let options = []
        let values = []
        if (props.isEdit) {
          if (list[i].handAddStatus === 1) {
            //编辑状态下获取手动添加编辑属性
            options = getEditAttrOptions(list[i].id)
          }
          //编辑状态下获取选中属性
          values = getEditAttrValues(i)
        }
        selectProductAttr.push({
          id: list[i].id,
          name: list[i].name,
          handAddStatus: list[i].handAddStatus,
          inputList: list[i].inputList,
          values: values,
          options: options
        })
      }
      if (props.isEdit) {
        //编辑模式下刷新商品属性图片
        refreshProductAttrPics()
      }
      type1.value = true
    } else {
      selectProductParam = reactive([])
      for (let i = 0; i < list.length; i++) {
        let value = null
        if (props.isEdit) {
          //编辑模式下获取参数属性
          value = getEditParamValue(list[i].id)
        }
        selectProductParam.push({
          id: list[i].id,
          name: list[i].name,
          value: value,
          inputType: list[i].inputType,
          inputList: list[i].inputList
        })
      }
      type2.value = true
    }
  })
}

//获取设置的可手动添加属性值
function getEditAttrOptions(id) {
  let options = []
  for (let i = 0; i < state.productAttributeValueList.length; i++) {
    let attrValue = state.productAttributeValueList[i]
    if (attrValue.productAttributeId === id) {
      let strArr = attrValue.value.split(',')
      for (let j = 0; j < strArr.length; j++) {
        options.push(strArr[j])
      }
      break
    }
  }
  return options
}

//获取选中的属性值
function getEditAttrValues(index) {
  let values = new Set()
  if (index === 0) {
    for (let i = 0; i < state.skuStockList.length; i++) {
      let sku = state.skuStockList[i]
      let spData = JSON.parse(sku.spData)
      if (spData != null && spData.length >= 1) {
        values.add(spData[0].value)
      }
    }
  } else if (index === 1) {
    for (let i = 0; i < state.skuStockList.length; i++) {
      let sku = state.skuStockList[i]
      let spData = JSON.parse(sku.spData)
      if (spData != null && spData.length >= 2) {
        values.add(spData[1].value)
      }
    }
  } else {
    for (let i = 0; i < state.skuStockList.length; i++) {
      let sku = state.skuStockList[i]
      let spData = JSON.parse(sku.spData)
      if (spData != null && spData.length >= 3) {
        values.add(spData[2].value)
      }
    }
  }
  return Array.from(values)
}

//获取属性的值
function getEditParamValue(id) {
  for (let i = 0; i < state.productAttributeValueList.length; i++) {
    if (id === state.productAttributeValueList[i].productAttributeId) {
      return state.productAttributeValueList[i].value
    }
  }
}
function handleProductAttrChange(value) {
  getProductAttrList(0, value[0])
  getProductAttrList(1, value[0])
}

function getInputListArr(inputList) {
  return inputList.split(',')
}

function handleAddProductAttrValue(idx) {
  let options = selectProductAttr[idx].options
  if (addProductAttrValue.value == null || addProductAttrValue.value == '') {
    ElMessage({
      message: '属性值不能为空',
      type: 'warning',
      duration: 1000
    })
    return
  }
  if (options.indexOf(addProductAttrValue.value) !== -1) {
    ElMessage({
      message: '属性值不能重复',
      type: 'warning',
      duration: 1000
    })
    return
  }
  selectProductAttr[idx].options.push(addProductAttrValue.value)
  addProductAttrValue.value = null
}

function handleRemoveProductAttrValue(idx, itemValue) {
  selectProductAttr[idx].options = selectProductAttr[idx].options.filter(function (item) {
    return item !== itemValue
  })
  selectProductAttr[idx].values = selectProductAttr[idx].values.filter(function (item) {
    return item !== itemValue
  })
  console.log(selectProductAttr[idx].values)
  console.log(selectProductAttr[idx].options)
}

function getProductSkuSp(row, index) {
  let spData = JSON.parse(row.spData)
  if (spData != null && index < spData.length) {
    return spData[index].value
  } else {
    return null
  }
}

function handleRefreshProductSkuList() {
  ElMessageBox.confirm('刷新列表将导致sku信息重新生成，是否要刷新', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    refreshProductAttrPics()
    refreshProductSkuList()
  })
}

function handleSyncProductSkuPrice() {
  ElMessageBox.confirm('将同步第一个sku的价格到所有sku,是否继续', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (state.skuStockList !== null && state.skuStockList.length > 0) {
      let tempSkuList = []
      tempSkuList = tempSkuList.concat(tempSkuList, state.skuStockList)
      let price = state.skuStockList[0].price
      for (let i = 0; i < tempSkuList.length; i++) {
        tempSkuList[i].price = price
      }
      state.skuStockList = reactive([])
      state.skuStockList = state.skuStockList.concat(state.skuStockList, tempSkuList)
    }
  })
}

function handleSyncProductSkuStock() {
  ElMessageBox.confirm('将同步第一个sku的库存到所有sku,是否继续', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (state.skuStockList !== null && state.skuStockList.length > 0) {
      let tempSkuList = []
      tempSkuList = tempSkuList.concat(tempSkuList, state.skuStockList)
      let stock = state.skuStockList[0].stock
      let lowStock = state.skuStockList[0].lowStock
      for (let i = 0; i < tempSkuList.length; i++) {
        tempSkuList[i].stock = stock
        tempSkuList[i].lowStock = lowStock
      }
      state.skuStockList = []
      state.skuStockList = state.skuStockList.concat(state.skuStockList, tempSkuList)
    }
  })
}

function refreshProductSkuList() {
  state.skuStockList = reactive([])
  let skuList = state.skuStockList
  //只有一个属性时
  if (selectProductAttr.length === 1) {
    let attr = selectProductAttr[0]
    for (let i = 0; i < attr.values.length; i++) {
      skuList.push({
        spData: JSON.stringify([{ key: attr.name, value: attr.values[i] }])
      })
    }
  } else if (selectProductAttr.length === 2) {
    let attr0 = selectProductAttr[0]
    let attr1 = selectProductAttr[1]
    for (let i = 0; i < attr0.values.length; i++) {
      if (attr1.values.length === 0) {
        skuList.push({
          spData: JSON.stringify([{ key: attr0.name, value: attr0.values[i] }])
        })
        continue
      }
      for (let j = 0; j < attr1.values.length; j++) {
        let spData = []
        spData.push({ key: attr0.name, value: attr0.values[i] })
        spData.push({ key: attr1.name, value: attr1.values[j] })
        skuList.push({
          spData: JSON.stringify(spData)
        })
      }
    }
  } else {
    let attr0 = selectProductAttr[0]
    let attr1 = selectProductAttr[1]
    let attr2 = selectProductAttr[2]
    for (let i = 0; i < attr0.values.length; i++) {
      if (attr1.values.length === 0) {
        skuList.push({
          spData: JSON.stringify([{ key: attr0.name, value: attr0.values[i] }])
        })
        continue
      }
      for (let j = 0; j < attr1.values.length; j++) {
        if (attr2.values.length === 0) {
          let spData = []
          spData.push({ key: attr0.name, value: attr0.values[i] })
          spData.push({ key: attr1.name, value: attr1.values[j] })
          skuList.push({
            spData: JSON.stringify(spData)
          })
          continue
        }
        for (let k = 0; k < attr2.values.length; k++) {
          let spData = []
          spData.push({ key: attr0.name, value: attr0.values[i] })
          spData.push({ key: attr1.name, value: attr1.values[j] })
          spData.push({ key: attr2.name, value: attr2.values[k] })
          skuList.push({
            spData: JSON.stringify(spData)
          })
        }
      }
    }
  }
}

function refreshProductAttrPics() {
  selectProductAttrPics = reactive([])
  if (selectProductAttr.length >= 1) {
    let values = selectProductAttr[0].values
    for (let i = 0; i < values.length; i++) {
      let pic = null
      if (props.isEdit) {
        //编辑状态下获取图片
        pic = getProductSkuPic(values[i])
      }
      selectProductAttrPics.push({ name: values[i], pic: pic })
      hasAttrPic.value = true
    }
  }
}

//获取商品相关属性的图片
function getProductSkuPic(name) {
  for (let i = 0; i < state.skuStockList.length; i++) {
    let spData = JSON.parse(state.skuStockList[i].spData)
    if (name === spData[0].value) {
      return state.skuStockList[i].pic
    }
  }
  return null
}

//合并商品属性
function mergeProductAttrValue() {
  state.productAttributeValueList = []
  for (let i = 0; i < selectProductAttr.length; i++) {
    let attr = selectProductAttr[i]
    if (attr.handAddStatus === 1 && attr.options != null && attr.options.length > 0) {
      state.productAttributeValueList.push({
        productAttributeId: attr.id,
        value: getOptionStr(attr.options)
      })
    }
  }
  for (let i = 0; i < selectProductParam.length; i++) {
    let param = selectProductParam[i]
    state.productAttributeValueList.push({
      productAttributeId: param.id,
      value: param.value
    })
  }
}

//合并商品属性图片
function mergeProductAttrPics() {
  for (let i = 0; i < selectProductAttrPics.length; i++) {
    for (let j = 0; j < state.skuStockList.length; j++) {
      let spData = JSON.parse(state.skuStockList[j].spData)
      if (spData[0].value === selectProductAttrPics[i].name) {
        state.skuStockList[j].pic = selectProductAttrPics[i].pic
      }
    }
  }
}

function getOptionStr(arr) {
  let str = ''
  for (let i = 0; i < arr.length; i++) {
    str += arr[i]
    if (i != arr.length - 1) {
      str += ','
    }
  }
  return str
}

function handleRemoveProductSku(index) {
  let list = state.skuStockList
  if (list.length === 1) {
    list.pop()
  } else {
    list.splice(index, 1)
  }
}

function handlePrev() {
  emits('prevStep', state)
}

function handleNext() {
  mergeProductAttrValue()
  mergeProductAttrPics()
  emits('nextStep', state)
}
</script>

<style scoped>
.littleMarginLeft {
  margin-left: 10px;
}

.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
